<template>
  <div>
    <el-container>
      <el-header height="30px">
        <el-row type="flex" justify="start" align="middle">
          <el-col :span="4" v-if="isAuth('web:category:saveBatch')">
            <el-switch
              v-model="draggable"
              active-color="#13ce66"
              inactive-color="#ff4949"
              active-text="开启拖拽"
              inactive-text="关闭拖拽"
            >
            </el-switch>
          </el-col>
          <el-col :span="3" v-if="isAuth('web:category:saveBatch')">
            <el-button type="primary" @click="saveBatch()">批量保存</el-button>
          </el-col>
          <el-col :span="3" v-if="isAuth('web:category:delete')">
            <el-button
              type="danger"
              @click="removeBatch()"
              :disabled="disabledRemoveBatch.length <= 0"
              >批量删除</el-button
            >
          </el-col>
        </el-row>
      </el-header>
      <el-main>
        <el-tree
          ref="treeList"
          :data="treeList"
          :props="props"
          node-key="id"
          show-checkbox
          :default-expanded-keys="expandedKeys"
          :draggable="draggable"
          :expand-on-click-node="false"
          @node-drop="handleDrop"
          @check-change="handleCheckChange"
        >
          <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span style="padding-left: 20px">
              <el-button
                v-if="isAuth('web:category:save')"
                type="text"
                size="mini"
                @click="() => save(node, data)"
              >
                添加
              </el-button>
              <el-button
                v-if="isAuth('web:category:update')"
                type="text"
                size="mini"
                @click="() => modify(node, data)"
              >
                编辑
              </el-button>
              <el-button
                v-if="
                  isAuth('web:category:delete') && node.childNodes.length === 0
                "
                type="text"
                size="mini"
                @click="() => remove(node, data)"
              >
                删除
              </el-button>
            </span>
          </span>
        </el-tree>
      </el-main>
    </el-container>
    <el-dialog
      :title="!formData.id ? '新增' : '修改'"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        :model="formData"
        :rules="rules"
        ref="formData"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="分类名称"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="priority">
          <el-input
            v-model.number="formData.priority"
            placeholder="排序"
            autocomplete="off"
            type="number"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="formDataSubmit()">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      props: {
        children: "children",
        label: "name"
      },
      treeList: [],
      disabledRemoveBatch: [],
      draggable: false,
      dialogFormVisible: false,
      expandedKeys: [],
      formData: {
        id: 0,
        name: "",
        parentId: "",
        priority: "",
        level: ""
      },
      categoryList: [],
      rules: {
        name: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        priority: [
          { required: true, message: "排序不能为空", trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              if (!Number.isInteger(value)) {
                callback(new Error("请输入数字值"));
              } else {
                if (value < 0) {
                  callback(new Error("数字必须大于等于0"));
                } else {
                  callback();
                }
              }
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  methods: {
    // 获取树形列表
    getTreeList() {
      this.$http({
        url: this.$http.adornUrl("/web/category/get/category/list"),
        method: "get"
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.treeList = data.data;
        } else {
          this.treeList = [];
        }
      });
    },
    // 初始化表单
    initFormData(id) {
      this.formData.id = id || 0;
      this.formData.priority = 0;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["formData"].resetFields();
        if (this.formData.id) {
          this.$http({
            url: this.$http.adornUrl(`/web/category/info/${this.formData.id}`),
            method: "get"
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.formData.name = data.category.name;
              this.formData.priority = data.category.priority;
            }
          });
        }
      });
    },
    // 添加
    save(node, data) {
      this.initFormData();
      this.formData.parentId = data.id;
      this.formData.level = data.level + 1;
    },
    // 修改
    modify(node, data) {
      this.initFormData(data.id);
      this.formData.parentId = data.parentId;
      this.formData.level = data.level + 1;
    },
    // 删除
    remove(node, data) {
      let ids = [data.id];
      this.$confirm(`确定对 [分类=${data.name}] 进行删除操作?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.$http({
          url: this.$http.adornUrl("/web/category/delete"),
          method: "post",
          data: this.$http.adornData(ids, false)
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.expandedKeys.push(data.parentId);
                this.getTreeList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      });
    },
    // 提交表单
    formDataSubmit() {
      this.$refs["formData"].validate(valid => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(
              `/web/category/${!this.formData.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.formData.id || undefined,
              name: this.formData.name,
              parentId: this.formData.parentId,
              priority: this.formData.priority,
              level: this.formData.level
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.dialogFormVisible = false;
                  this.expandedKeys.push(this.formData.parentId);
                  this.getTreeList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
          });
        }
      });
    },
    // 处理拖拽
    handleDrop(draggingNode, dropNode, dropType, ev) {
      let category = {
        id: 0,
        name: "",
        parentId: "",
        priority: "",
        level: ""
      };
      if (dropType === "inner") {
        let id = draggingNode.data.id;
        let name = draggingNode.data.name;
        let parentId = dropNode.data.id;
        let level = dropNode.data.level + 1;
        let priority = dropNode.data.children.length;
        this.handleChildren(dropNode, dropNode.childNodes);
        let children = draggingNode.data.children;
        category.id = id;
        category.name = name;
        category.parentId = parentId;
        category.level = level;
        category.priority = priority;
        this.categoryList.push(category);
        this.addChildrenToCategoryList(children);
      } else {
        let id = draggingNode.data.id;
        let name = draggingNode.data.name;
        let parentId = dropNode.data.parentId;
        let level = dropNode.data.level;
        let priority;
        if (dropType === "after") {
          priority = dropNode.data.priority + 1;
        } else {
          priority = dropNode.data.priority - 1;
        }
        this.handleChildren(dropNode.parent, dropNode.parent.childNodes);
        let children = draggingNode.data.children;
        category.id = id;
        category.name = name;
        category.parentId = parentId;
        category.level = level;
        category.priority = priority;
        this.categoryList.push(category);
        this.addChildrenToCategoryList(children);
      }
    },
    // 递归修改层级和parentId
    handleChildren(parentNode, childNodes) {
      let parentLevel = parentNode.data.level;
      let id = parentNode.data.id;
      if (childNodes.length > 0) {
        for (const childNode of childNodes) {
          childNode.data.level = parentLevel + 1;
          childNode.data.parentId = id;
          this.handleChildren(childNode, childNode.childNodes);
        }
      }
    },
    // 递归添加子节点到categoryList中
    addChildrenToCategoryList(childrens) {
      for (const children of childrens) {
        for (let index = 0; index < this.categoryList.length; index++) {
          const category = this.categoryList[index];
          if (category.id === children.id) {
            this.categoryList.splice(index, 1);
          }
        }
        this.categoryList.push(children);
        this.addChildrenToCategoryList(children.children);
      }
    },
    // 批量保存
    saveBatch() {
      let categoryList = this.categoryList;
      if (categoryList.length > 0) {
        this.$http({
          url: this.$http.adornUrl("/web/category/saveBatch"),
          method: "post",
          data: this.$http.adornData({ categoryList })
        }).then(({ data }) => {
          if (data && data.code === 0) {
            this.$message({
              message: "操作成功",
              type: "success",
              duration: 1500,
              onClose: () => {
                this.expandedKeys.push(
                  categoryList[categoryList.length - 1].parentId
                );
                this.categoryList = [];
                this.getTreeList();
              }
            });
          } else {
            this.$message.error(data.msg);
          }
        });
      } else {
        this.$message.error("请开启拖拽功能, 进行修改");
      }
    },
    // 批量删除
    removeBatch() {
      let checkedNodes = this.$refs.treeList.getCheckedNodes(false, false);
      let ids = [];
      let parentIds = [];
      let names = [];
      for (const node of checkedNodes) {
        ids.push(node.id);
        names.push(node.name);
        parentIds.push(node.parentId);
      }
      if (ids.length > 0) {
        this.$confirm(`确定对 [分类=${names.join(',')}] 进行批量删除操作?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.$http({
            url: this.$http.adornUrl("/web/category/delete"),
            method: "post",
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.expandedKeys.push(parentIds[0]);
                  this.getTreeList();
                }
              });
            } else {
              this.$message.error(data.msg);
            }
            this.disabledRemoveBatch = [];
          });
        });
      } else {
        this.$message.error("请至少选择一项");
        this.disabledRemoveBatch = [];
      }
    },
    // 处理选中事件
    handleCheckChange() {
      this.disabledRemoveBatch = [];
      let checkedNodes = this.$refs.treeList.getCheckedNodes(false, false);
      for (const node of checkedNodes) {
        this.disabledRemoveBatch.push(node.id);
      }
    }
  },
  activated() {
    this.getTreeList();
  }
};
</script>
